package com.zlc.common.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.username:#{null}}")
    private String username;
    @Value("${spring.redis.password}")
    private String password;
    private String lockPrefix;


    @Value("${spring.application.name:unknown}")
    private void setProjectName(String projectName) {
        this.lockPrefix = projectName + ":lock:";
    }

    @Bean(
            name = {"mayanRedissonClient"}
    )
    public RedissonClient redissonClient() {
        if (this.username == null) {
            String[] usernameAndPassword = this.password.split(":", 2);
            if (usernameAndPassword.length == 2) {
                this.username = usernameAndPassword[0];
                this.password = usernameAndPassword[1];
            }
        }

        Config config = new Config();
        ((SingleServerConfig) config.useSingleServer().setAddress("redis://" + this.host + ":" + this.port).setUsername(this.username)).setPassword(this.password);
        return Redisson.create(config);
    }

    public String getLockPrefix() {
        return lockPrefix;
    }
}
